<template>
    <div id="user">
        <div class="box">
            <div class="first">
                <div class="logo"></div>
                <div class="title">个人资料</div>
            </div>
            <div class="second">
                <div class="input">
                    <a-form :model="formState" name="basic">
                        <div class="one"
                            style="width: 100%;height: 90px; display: flex;justify-content: space-between; align-items: center;">
                            <div style="width: 30%; height: 45px; ">
                                <a-form-item label="姓名" name="username" style="display: flex; align-items: center;"
                                    :rules="[{ required: true, message: '请输入姓名！' }]">
                                    <a-input v-model:value="formState.username" placeholder="请输入手机号"
                                        style="height: 45px;" />
                                </a-form-item>
                            </div>
                            <div style="width: 30%; height: 45px;">
                                <a-form-item label="员工编号" name="code" style="display: flex; align-items: center;"
                                    :rules="[{ required: true, messag: '请输入手机号！' }]">
                                    <a-input :disabled="true" v-model:value="formState.code" placeholder="请输入手机号"
                                        style="height: 45px;" />
                                </a-form-item>
                            </div>
                            <div class="avatar"
                                style="width: 30%; display: flex; justify-content: center; align-items: center;">
                                <div>头像：</div>
                                <div>
                                    <a-upload v-model:file-list="fileList" name="avatar" list-type="picture-card"
                                        class="avatar-uploader" :show-upload-list="false"
                                        action="http://localhost:3000/upload" :before-upload="beforeUpload"
                                        @change="handleChange">
                                        <img style="width: 50px; height:50px;" v-if="formState.imgUrl"
                                            :src="formState.imgUrl" alt="avatar" />
                                        <div v-else>
                                            <loading-outlined v-if="loading"></loading-outlined>
                                            <plus-outlined v-else></plus-outlined>
                                            <div class="ant-upload-text">Upload</div>
                                        </div>
                                    </a-upload>
                                </div>
                            </div>
                        </div>
                        <div class="two"
                            style="width: 100%;height: 90px; display: flex;gap: 55px; align-items: center;">
                            <div style="width: 30%; height: 45px; ">
                                <a-form-item label="手机号" name="phone" style="display: flex; align-items: center;"
                                    :rules="[{ required: true, message: '请输入手机号！' }, { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号！' }]">
                                    <a-input v-model:value="formState.phone" placeholder="请输入手机号"
                                        style="height: 45px;" />
                                </a-form-item>
                            </div>
                            <div style="width: 30%; height: 45px;">
                                <a-form-item label="角色" name="roleid">
                                    <a-select v-model:value="formState.roleid" :disabled="true" placeholder="请选择角色">
                                        <a-select-option v-for="item in roleList" :key="item._id" :value="item._id"
                                            style="height: 45px;">{{
                                                item.name }}</a-select-option>
                                    </a-select>
                                </a-form-item>
                            </div>
                        </div>
                        <div class="four">
                            <a-form-item label="备注" name="desc">
                                <a-textarea v-model:value="formState.remark" />
                            </a-form-item>
                        </div>
                    </a-form>
                </div>
            </div>
            <div class="third">
                <button @click="handleSave">保存</button>
            </div>
        </div>
    </div>
</template>
<script setup lang="ts">
import { reactive, ref } from 'vue';

//上传头像
import { PlusOutlined, LoadingOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import type { UploadChangeParam, UploadProps } from 'ant-design-vue';
import router from '@/router';
import houseApi from '@/axios';

function getBase64(img: Blob, callback: (base64Url: string) => void) {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result as string));
    reader.readAsDataURL(img);
}

const fileList = ref([]);
const loading = ref<boolean>(false);
const handleChange = (info: UploadChangeParam) => {
    console.log(info);

    if (info.file.status === 'uploading') {
        loading.value = true;
        return;
    }
    if (info.file.status === 'done') {
        // Get this url from response in real world.
        getBase64(info.file.originFileObj, (base64Url: string) => {
            formState.imgUrl = base64Url;
            loading.value = false;
        });
    }
    if (info.file.status === 'error') {
        loading.value = false;
        message.error('upload error');
    }
};

const beforeUpload = (file: UploadProps['fileList'][number]) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
        message.error('You can only upload JPG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
        message.error('Image must smaller than 2MB!');
    }
    return isJpgOrPng && isLt2M;
};


//表单框
interface FormState {
    _id: string;
    username: string;
    code: string;
    phone: string;
    status: boolean;
    remark: string;
    roleid: string;
    imgUrl: string;
    password: string;
    createTime: Date;
}

const formState = reactive<FormState>({
    _id: '',
    username: '',
    code: '',
    phone: '',
    status: true,
    remark: '',
    roleid: '',
    imgUrl: '',
    password: '',
    createTime: new Date()
});


// 定义 User 类型，表示用户对象的结构 
type User = {
    _id: string,
    username: string,
    code: string,
    imgUrl: string,
    phone: string,
    password: string
    status: Boolean,
    createTime: Date,
    remark: string,
    roleid: string
}

// 创建一个函数类型，返回 User 对象或字符串  
type GetUserFunction = () => User | string;

// 函数实现，用于获取用户信息  
const getUser: GetUserFunction = () => {
    const storedUser = localStorage.getItem('user');
    // 判断用户信息是否存在，如果存在则解析为对象，否则返回"未登录"  
    return storedUser ? JSON.parse(storedUser) : '未登录';
};

// 获取用户初始化数据，并将其放入 reactive 中  
let user = reactive(getUser());

formState._id = user._id;
formState.username = user.username;
formState.code = user.code;
formState.phone = user.phone;
formState.status = user.status;
formState.remark = user.remark;
formState.roleid = localStorage.getItem('roleid');
formState.imgUrl = user.imgUrl;
formState.password = user.password;
formState.createTime = user.createTime;

//获取角色
let roleList: any[] = [];
const getRoleList = async () => {
    const { data: { code, data } } = await houseApi.get('/rolelist');
    if (code === 200) {
        roleList = data;
    }
}
getRoleList();


const handleSave = async () => {
    const { data: { code, msg } } = await houseApi.post('/changeInfo', formState)
    if (code === 200) {
        localStorage.setItem('user', JSON.stringify(formState));
        message.success(msg);
        router.push('/set/suser');
    }
}

</script>
<style scoped lang="scss">
#user {
    width: 100%;
    height: 93.5vh;
    background-color: #F2FBFA;
    position: relative;

    .box {
        width: 80%;
        height: 600px;
        background-color: #fff;
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -65%);
        border-radius: 10px;
        box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);

        .first {
            width: 100%;
            height: 10%;
            display: flex;
            gap: 15px;
            align-items: center;
            padding: 0 20px;
            box-sizing: border-box;

            .logo {
                width: 7px;
                height: 25px;
                background-color: #3DD4A7;
                border-radius: 5px;
            }

            .title {
                font-size: 21px;
                color: #3f3f3f;
                font-weight: 500;
            }
        }

        .second {
            width: 100%;
            height: 75%;
            padding: 0 20px;
            box-sizing: border-box;
            border-top: 1px solid #EBEBEB;
            border-bottom: 1px solid #EBEBEB;
            overflow: hidden;

            .input {
                margin-top: 40px;
            }
        }

        .third {
            width: 100%;
            height: 15%;
            padding: 0 20px;
            box-sizing: border-box;
            display: flex;
            align-items: center;

            button {
                width: 70px;
                height: 40px;
                border-radius: 5px;
                border: none;
                background-color: #3DD4A7;
                color: #fff;
                font-size: 16px;
                cursor: pointer;
            }
        }
    }
}
</style>
